package com.nsi.service.Impl;

import com.google.gson.JsonObject;
import com.nsi.common.Const;
import com.nsi.util.RedisUtils;
import com.nsi.common.ResponseCode;
import com.nsi.common.ServerResponse;
import com.nsi.exception.NsiOperationException;
import com.nsi.service.AccessTokenService;
import com.nsi.service.MsgCheckService;
import com.nsi.util.Httpsrequest;
import com.nsi.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Luo Zhen
 * @create 2020-01-09 17:12
 */
@Slf4j
@Service
public class MsgCheckServiceImpl implements MsgCheckService {

    public static final Integer SUCCESS_CODE = 0;

    @Autowired
    private AccessTokenService accessTokenService;

    @Override
    public String getToken(String appId, String appSecret, String prefix) throws Exception {
        String accessToken = RedisUtils.searchRedis(prefix);
        if (StringUtils.isEmpty(accessToken)) {
            accessToken = accessTokenService.getAccessToken(appId, appSecret);
            // 存入redis
            RedisUtils.expireSet(prefix, Const.EXPIRE_TIME, accessToken);
        }
        return accessToken;
    }

    @Override
    public ServerResponse msgSecCheck(String accessToken, String content) {
        String requestUrl = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;
        String param = "{\"content\":\"" + content + "\"}";
        String responseJson;
        try {
            responseJson = Httpsrequest.httpsRequest(requestUrl, "POST", param);
        } catch (Exception e) {
            log.error("【微信小程序验证内容失败】:{}", e);
            throw new NsiOperationException(ResponseCode.SERVER_ERROR);
        }
        JsonObject jsonObject = JsonUtils.getJsonObject(responseJson);
        System.out.println(responseJson);
        Integer code = Integer.parseInt(jsonObject.get("errcode").getAsString());
        if (SUCCESS_CODE.equals(code)) {
            return ServerResponse.createBySuccessMessage("校验成功!");
        } else {
            return ServerResponse.createByErrorMessage("非法字符!");
        }
    }
}
